package com.jwj.testback.recordsheet.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jwj.testback.recordsheet.dao.DatasourceMapper;
import com.jwj.testback.recordsheet.pojo.Datasource;
import com.jwj.testback.recordsheet.pojo.TableField;
import com.jwj.testback.recordsheet.pojo.Tableware;
import com.jwj.testback.recordsheet.service.DatasourceService;
import com.jwj.testback.util.IP;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author JWJ
 * @since 2021-12-21
 */
@Service
public class DatasourceServiceImpl extends ServiceImpl<DatasourceMapper, Datasource> implements DatasourceService {


//    public static final String filePre = System.getProperty("user.dir")+"/backupsql/";
    //window
//    public static final String filePre = System.getProperty("user.dir")+"/testback/src/main/resources/static/backupsql/";
    //linux
    public static final String filePre = System.getProperty("user.dir")+"/src/main/resources/static/backupsql/";

    public static final String PRE = "jdbc:mysql://"+IP.Ip+":3306/";

    public static final String Suffix = "?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf-8";


    @Override
    public List<Datasource> showDataBases() {
        showAllBases();
        List<Datasource> datasources = baseMapper.showDataBases();
        return datasources;
    }

    //显示所有数据库
    @Override
    public void showAllBases() {
        Datasource datasource = new Datasource();

        //先查询test0的datasource里有没有数据库
        List<Datasource> nowBase = baseMapper.showDataBases();
        //判断存放数据库表里是否有数据,判断list 是否为空
        boolean empty = CollectionUtils.isNotEmpty(nowBase);
        //map实例
        Map<String,String> baseMap = new HashMap<>();
        baseMap.put("information_schema","information_schema");
        baseMap.put("performance_schema","performance_schema");
        baseMap.put("mysql","mysql");
        baseMap.put("sys","sys");

        if (empty){
            //法1： 如果有数据，就把dsname放入map里
            //法2： 如果有数据，就清空表
            //
            for (int i = 0; i < nowBase.size(); i++) {
//                String bsName = nowBase.get(i).getDsname();
//                baseMap.put(bsName,bsName);
                baseMapper.clearOneTb();
            }
        }
        List<String> allBases = baseMapper.showAllBases();
        for (int i = 0; i < allBases.size(); i++) {
            //先判断map里是否有这个数据库的key
            boolean b = baseMap.containsKey(allBases.get(i));
            //如果没有这个key，就把这个key放入map里并添加到数据库中
            if (b==false){
                datasource.setType("com.alibaba.druid.pool.DruidDataSource");
                datasource.setDriverClassName("com.mysql.cj.jdbc.Driver");
                datasource.setUsername(IP.username);
                datasource.setPassword(IP.password);
                datasource.setStatus("1");
                datasource.setUrl(PRE +allBases.get(i) + Suffix);
                datasource.setDsname(allBases.get(i));

                baseMapper.insert(datasource);
                baseMap.put(allBases.get(i),allBases.get(i));
            }
        }
        for(String key:baseMap.keySet()){
            //遍历map，判断list里是否有map的key，没有的key就在datasource里删除记录
            boolean contains = allBases.contains(key);
            if (contains==false){
                baseMapper.delDsname(key);
            }
        }
    }

    @Override
    public List<Tableware> showTables(String databaseName) {
        List<Tableware> list = baseMapper.showTables(databaseName);
        return list;
    }

    @Override
    public List<Tableware> TableSize(String databaseName) {
        String filePath = filePre + databaseName;
        List<Tableware> wareList = new ArrayList<>();
        try {
            File file = new File(filePath);
            // 获得该文件夹内的所有文件
            File[] array = file.listFiles();
            for (int i = 0; i < array.length; i++) {
                if (array[i].isFile())//如果是文件
                {
                    Tableware tableware = new Tableware();
                    File f = new File(array[i].getPath());
                    String fileName = f.getName();
                    long length = f.length();
//                    System.out.println("文件"+fileName+"的大小是："+getPrintSize(length));
                    tableware.setTableName(fileName);
                    tableware.setTbSize(getPrintSize(length));
                    tableware.setFiPath("/static/backupsql/"+databaseName+"/"+fileName);

                    wareList.add(tableware);
                }
                else {
                    return null;
                }
            }
        }catch (Exception e){
            System.out.println("文件夹没数据");
            return wareList;
        }
        return wareList;
    }

    @Override
    public List<TableField> showField(String tableName,String databaseName) {
        List<TableField> tableFields = baseMapper.showField(tableName,databaseName);
        return tableFields;
    }

    @Override
    public Datasource showNamePas(String databaseName) {
        Datasource datasource = baseMapper.showNamePas(databaseName);
        return datasource;
    }

    public static String getPrintSize(long size) {
        //如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        //如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
        //因为还没有到达要使用另一个单位的时候
        //接下去以此类推
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            //因为如果以MB为单位的话，要保留最后1位小数，
            //因此，把此数乘以100之后再取余
            size = size * 100;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "MB";
        } else {
            //否则如果要以GB为单位的，先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "GB";
        }
    }
}
